<!DOCTYPE HTML>
<html lang="zh" xmlns:th="http://www.thymeleaf.org" xmlns:shiro="http://www.pollix.at/thymeleaf/shiro">
<meta charset="utf-8">
<head th:include="include :: header"></head>
<body class="gray-bg">

<div class="container-div">
    <div class="row">
        <div class="col-sm-12 search-collapse">
            <form id="formId">
                <input id="treeId" name="moduleId" type="hidden" th:value="${projectCaseModule.moduleId}"/>
                <div class="select-list">
                    <ul>

                        <li>
                            <select id="projectId" name="relProjectId" th:with="type=${projects}"
                                    onchange="initializeModuleTree()">
                                <option value="">所有项目</option>
                                <option th:each="projects : ${type}" th:text="${projects.projectName}"
                                        th:value="${projects.projectId}"
                                        th:selected="${projects.projectId == defaultProjectId}"></option>
                            </select>
                        </li>


                        <li>
                            模块：
                            <input type="text" onclick="selectModuleTree()" id="treeName" readonly="true" value=""/>
                        </li>

                        <li>
                            计划名称：<input type="text" name="name"/>
                        </li>

                        <li>
                            创建者：<input type="text" name="createBy"/>
                        </li>



                        <li>
                            备注：<input type="text" name="remark"/>
                        </li>

                        <li>
                            <a class="btn btn-primary btn-rounded btn-sm" onclick="$.table.search()"><i
                                    class="fa fa-search"></i>&nbsp;搜索</a>
                            <a class="btn btn-warning btn-rounded btn-sm" onclick="$.form.reset()"><i
                                    class="fa fa-refresh"></i>&nbsp;重置</a>
                        </li>
                    </ul>
                </div>
            </form>
        </div>

        <div class="btn-group-sm hidden-xs" id="toolbar" role="group">
            <a class="btn btn-success" onclick="$.operate.add()" shiro:hasPermission="jmeter:jmeterTestPlan:add">
                <i class="fa fa-plus"></i> 添加
            </a>
            <a class="btn btn-primary btn-edit disabled" onclick="$.operate.edit()"
               shiro:hasPermission="jmeter:jmeterTestPlan:edit">
                <i class="fa fa-edit"></i> 修改
            </a>
            <a class="btn btn-danger btn-del btn-del disabled" onclick="$.operate.removeAll()"
               shiro:hasPermission="jmeter:jmeterTestPlan:remove">
                <i class="fa fa-remove"></i> 删除
            </a>
            <a class="btn btn-primary btn-del btn-del disabled" onclick="startJmeter()">
                <i class="fa fa-play"></i> 立即执行
            </a>
            <a class="btn btn-info btn-edit disabled" onclick="showPlanCase()">
                <i class="fa fa-edit"></i> 计划用例
            </a>
        </div>
        <div class="col-sm-12 select-table table-striped">
            <table id="bootstrap-table" data-mobile-responsive="true"></table>
        </div>
    </div>
</div>
<div th:include="include :: footer"></div>
<script th:inline="javascript">
    var editFlag = [[${@permission.hasPermi('jmeter:jmeterTestPlan:edit')}]];
    var removeFlag = [[${@permission.hasPermi('jmeter:jmeterTestPlan:remove')}]];
    var prefix = ctx + "jmeter/jmeterTestPlan";
    var planRecordPrefix = ctx + "jmeter/jmeterTestPlanRecord";
    var aletConfigPrefix = ctx + "jmeter/jmeterTestPlanRecord";
    var modulePrefix = ctx + "testmanagmt/projectCaseModule";


    $(function () {
        var options = {
            url: prefix + "/list",
            createUrl: prefix + "/add",
            updateUrl: prefix + "/edit/{id}",
            removeUrl: prefix + "/remove",
            exportUrl: prefix + "/export",
            modalName: "jmx测试计划",
            search: false,
            showExport: true,
            columns: [{
                checkbox: true
            },
                {
                    field: 'id',
                    title: 'id',
                    visible: false
                },
				{
					field : 'relProjectName',
					title : '项目名称',
					sortable: true
				},
                {
                    field: 'relModuleName',
                    title: '模块名称',
                    sortable: true
                },
                {
                    field: 'interfaceName',
                    title: '接口名称',
                    sortable: true
                },
                {
                    field: 'name',
                    title: '计划名称',
                    sortable: true
                },
                {
                    field: 'jobType',
                    title: '执行策略',
                    sortable: true,
                    formatter: function (value) {
                        if (value == 0) {
                            return '未设置执行策略';
                        } else if (value == 1) {
                            return '指定时间执行';
                        } else if (value == 2) {
                            return '按照cron表达式执行';
                        }
                        return '类型错误';
                    }
                },
                {
                    field: '立即执行',
                    title: '立即执行',
                    formatter:function (value,row) {
                        var actions = [];
                        actions.push('<a class="btn btn-success btn-xs ' + editFlag + '" href="#" onclick="startById(\'' + row.id + '\')"><i class="fa fa-edit"></i>立即执行</a> ');
                        return actions.join('');
                    }
                },
                {
                    field: 'cronExpr',
                    title: 'cron表达式',
                    sortable: true
                },
                {
                    field: 'scheduledTime',
                    title: '指定执行时间',
                    sortable: true
                },

                {
                    field: 'cronJobStatus',
                    title: '任务状态',
                    align: 'center',

                    formatter: function (value, row) {
                        if (value == 0) {
                            var hdiv = '<span id="statusSpan' + row.id + '" class="glyphicon " style="color: rgba(40,127,23,0.98);"> 运行中</span>';
                        } else {
                            var hdiv = '<span id="statusSpan' + row.id + '" class="glyphicon " style="color: rgba(119,58,175,0.91);"> 暂停中</span>';
                        }
                        return '<font id="statusFont' + row.id + '">' + hdiv + '</font>';
                    }
                },
                {
                    field: 'testPurpose',
                    title: '测试目的',
                    sortable: false
                },
                {
                    field: 'scenario',
                    title: '测试场景',
                    sortable: false
                },
                {
                    field: 'createBy',
                    title: '创建者',
                    sortable: true
                },
                {
                    field: 'updateBy',
                    title: '更新者',
                    sortable: true
                },
                {
                    field: 'remark',
                    title: '备注',
                    sortable: true
                },
                {
                    title: '操作',
                    align: 'center',
                    // events: window.operateEvents,/
                    formatter: function (value, row, index) {
                        var actions = [];

                        if (row.jobType != 0) {
                            if (row.cronJobStatus == 0) {
                                actions.push('<a class="btn btn-success btn-xs ' + editFlag + '" href="#" onclick="pauseJob(\'' + row.id + '\')"><i class="fa fa-pause"></i>暂停</a> ');
                            } else {
                                actions.push('<a class="btn btn-success btn-xs ' + editFlag + '" href="#" onclick="resumeJob(\'' + row.id + '\')"><i class="fa fa-reorder"></i>恢复</a> ');
                            }
                        }

                        actions.push('<a class="btn btn-success btn-xs ' + editFlag + '" href="#" onclick="$.operate.edit(\'' + row.id + '\')"><i class="fa fa-edit"></i>编辑</a> ');
                        actions.push('<a class="btn btn-danger btn-xs ' + removeFlag + '" href="#" onclick="$.operate.remove(\'' + row.id + '\')"><i class="fa fa-remove"></i>删除</a>');
                        actions.push('<a class="btn btn-success btn-xs ' + editFlag + '" href="#" onclick="seeRecord(\'' + row.id + '\')"><i class="fa fa-edit"></i>查看执行记录</a> ');
                        return actions.join('');
                    }
                }]
        };
        $.table.init(options);
    });


    function doSubmit(index, layero) {
        var body = layer.getChildFrame('body', index);
        $("#treeId").val(body.find('#treeId').val());
        $("#treeName").val(body.find('#treeName').val());
        layer.close(index);
    }


    /*查询条件选择用例模块*/
    function selectModuleTree() {
        var projectId = $("#projectId  option:selected").val();
        if (projectId == "") {
            $.modal.alertError("请先选择项目");
        } else {
            var options = {
                title: '模块选择',
                width: "380",
                url: modulePrefix + "/selectProjectCaseModuleTree/" + $("#treeId").val(),
                callBack: doSubmit
            };
            $.modal.openOptions(options);
        }
    }

    /*选择项目初始化模块树*/
    function initializeModuleTree() {
        var projectId = $("#projectId  option:selected").val();
        if (projectId == "") {
            $("#treeId").val("");
            $("#treeName").val("");
        } else {
            $.ajax({
                cache: true,
                type: "GET",
                url: modulePrefix + "/getModuleByProjectId/" + projectId,
                data: {},
                async: false,
                error: function (request) {
                    $.modal.alertError("系统错误");
                },
                success: function (data) {
                    $("#treeId").val(data.moduleId);
                    $("#treeName").val(data.moduleName);
                }
            });
        }
    }

    function resetForm() {
        initializeModuleTree();
        $.form.reset();
    }


    function showPlanCase() {
        var row = $.map($('#bootstrap-table').bootstrapTable('getSelections'), function (row) {
            return row;
        });

        var url = "/404.html";
        if ($.common.isNotEmpty(row)) {

            var url = prefix + "/selectTestCase?planId=" + row[0].id;
            openFull(row[0].id, "[" + row[0].name + "]", url);
        }
    }

    function openFull(planId, title, url, width, height) {
        //如果是移动端，就使用自适应大小弹窗
        if (navigator.userAgent.match(/(iPhone|iPod|Android|ios)/i)) {
            width = 'auto';
            height = 'auto';
        }
        var index = layer.open({
            type: 2,
            area: [width + 'px', height + 'px'],
            fix: false,
            //不固定
            maxmin: true,
            shade: 0.3,
            title: title,
            content: url,
            btn: ["保存选择用例", '关闭'],
            // 弹层外区域关闭
            shadeClose: true,
            yes: function (index, layero) {
                var iframeWin = layero.find('iframe')[0];
                iframeWin.contentWindow.submitHandler(planId, index);
                return true;
            },
            cancel: function (index) {
                return true;
            }
        });
        layer.full(index);
    }


    function startJmeter() {
        let arr = $('#bootstrap-table').bootstrapTable('getSelections');
        if (arr.length == 0) {
            $.modal.alertWarning("请至少选择一条记录");
            return;
        }
        var idlist = arr.map(it => it.id);
        startById(idlist)
    }



    function startById(id) {
        let arr=[]
        if(Array.isArray(id)){
            arr=id
        }else{
            arr.push(id)
        }
        var config = {
            url: prefix + "/startJmeters",
            type: "post",
            dataType: "json",
            contentType: "application/json",
            data: JSON.stringify(arr),
            beforeSend: function () {
            },
            success: function (result) {
                $.table.refresh();
                $.modal.msgSuccess(result.msg);
                $.treeTable.refresh();
                $.modal.closeLoading();
                $.modal.enable();
            }
        };
        $.ajax(config);
    }



    function seeRecord(planId) {
        window.location.href = planRecordPrefix + "?relPlanId=" + planId;
    }


    function pauseJob(planId) {
        switchJobStatus(planId, "1", "/pauseJob");
    }


    function resumeJob(planId) {
        switchJobStatus(planId, "0", "/resumeJob");
    }


    function switchJobStatus(planId, status, url) {

        let obj = {};
        obj.id = planId;
        obj.cronJobStatus = status;

        var config = {
            url: prefix + url,
            type: "post",
            dataType: "json",
            contentType: "application/json",
            data: JSON.stringify(obj),
            beforeSend: function () {
            },
            success: function (result) {
                $.modal.msgSuccess(result.msg);
                $.table.refresh();
            }
        };
        $.ajax(config);
    }


</script>
</body>
</html>